import React from 'react';
import {Editor, ShortcutKey} from 'amis-editor';
import {inject, observer} from 'mobx-react';
import {RouteComponentProps} from 'react-router-dom';
import {toast, Select, utils} from 'amis';
import {currentLocale} from 'i18n-runtime';
import {Icon} from '../icons/index';
import {IMainStore, IPage} from '../store';
import '../editor/DisabledEditorPlugin'; // 用于隐藏一些不需要的Editor预置组件
import '../renderer/MyRenderer';
import '../editor/MyRenderer';
import {CenterApi} from '../xaas/api/ResourceApi';
import {useCache} from '../xaas/utils/useCache';

let currentIndex = -1;

let currentResId: string = '';

let host = `${window.location.protocol}//${window.location.host}`;

// 如果在 gh-pages 里面
if (/^\/amis-editor-demo/.test(window.location.pathname)) {
  host += '/amis-editor';
}

const schemaUrl = `${host}/schema.json`;

const editorLanguages = [
  {
    label: '简体中文',
    value: 'zh-CN'
  },
  {
    label: 'English',
    value: 'en-US'
  }
];

let formDsgnId = 0;

const {wsCache} = useCache('sessionStorage');
const paramsObj: {[key: string]: string} = {};


export default inject('store')(
  observer(function ({
    store,
    location,
    history,
    match
  }: {store: IMainStore} & RouteComponentProps<{id: string}>) {
    let resId: string = match.params.id;
    // const index: number = parseInt(match.params.id, 10);
    const curLanguage = currentLocale(); // 获取当前语料类型
    if (resId !== currentResId) {
      currentResId = resId;
      CenterApi.getDsgnById(resId).then(res => {
        if (res.formDsgnId) {
          formDsgnId = res.formDsgnId;
        }
        if (res.form) {
          let pages = store.pages;
          let page = pages.find(p => p.id == resId);
          if (!page) {
            let newPage = {
              id: resId,
              label: res.basic.title,
              appDsgnId: res.basic.dsgnId,
              formDsgnId: res.formDsgnId,
              path: resId,
              icon: JSON.stringify(res.basic.icon),
              schema: res.form.configJson
            };
            store.addPage(newPage, resId);
            store.updateSchema({});
          }
          store.updateSchema(res.form.configJson);
          store.updatePageSchemaById(res.form.configJson, resId);
          wsCache.set(resId, res.form.configJson);
          // store.updatePageSchemaAt(index);
        } else {
          store.updateSchema({});
          wsCache.set(resId, {});
        }
      });
    }

    function save() {
      store.updatePageSchemaById(store.schema, resId);
      // wsCache.set(resId, schema);
      toast.success('保存成功', '提示');
    }

    function onChange(value: any) {
      store.updateSchema(value);
      store.updatePageSchemaById(value, resId);
      // wsCache.set(resId, value);
      // store.updatePageSchemaAt(index);
    }

    function changeLocale(value: string) {
      localStorage.setItem('suda-i18n-locale', value);
      window.location.reload();
    }

    function exit() {
      const page = store.getPageByResId(resId);
      if (page) {
        history.push(`/${page.path}`);
      } else {
        // 处理页面为 undefined 的情况，比如日志记录或路由到默认页面
        console.error(`页面资源 ID 为 ${resId} 的页面未找到`);
        history.push('/default'); // 假设有一个默认的路径
      }
    }

    // 保存到数据库
    function onSaveOrUpdate(this: any, e: any) {
      if (resId) {
        // store.updatePageSchemaAt(index);
        let schema = store.schema;

        if (formDsgnId < 1) {
          toast.error('不允许的操作', '提示');
          return;
        }

        let page = store.getPageByResId(resId);
        if (page) {
          CenterApi.updateFormData({
            id: formDsgnId,
            appDsgnId: page.appDsgnId,
            content: schema
          })
            .then(r => {
              toast.success('操作成功！', '提示');
            })
            .catch(e => {
              console.log(e);
              toast.error('服务器异常，请联系管理员！', '提示');
            });
        }
      }
    }

    return (
      <div className="Editor-Demo">
        <div className="Editor-header">
          <div className="Editor-title"></div>
          <div className="Editor-view-mode-group-container">
            <div className="Editor-view-mode-group">
              <div
                className={`Editor-view-mode-btn editor-header-icon ${
                  !store.isMobile ? 'is-active' : ''
                }`}
                onClick={() => {
                  store.setIsMobile(false);
                }}
              >
                <Icon icon="pc-preview" title="PC模式" />
              </div>
              <div
                className={`Editor-view-mode-btn editor-header-icon ${
                  store.isMobile ? 'is-active' : ''
                }`}
                onClick={() => {
                  store.setIsMobile(true);
                }}
              >
                <Icon icon="h5-preview" title="移动模式" />
              </div>
            </div>
          </div>

          <div className="Editor-header-actions">
            <ShortcutKey />
            <Select
              className="margin-left-space"
              options={editorLanguages}
              value={curLanguage}
              clearable={false}
              onChange={(e: any) => changeLocale(e.value)}
            />
            <div
              className={`header-action-btn m-1 ${
                store.preview ? 'primary' : ''
              }`}
              onClick={() => {
                store.setPreview(!store.preview);
              }}
            >
              {store.preview ? '编辑' : '预览'}
            </div>

            {
              <div
                className={`header-action-btn m-1 primary`}
                onClick={(e: any) => onSaveOrUpdate(e)}
              >
                保存
              </div>
            }

            {!store.preview && (
              <div className={`header-action-btn exit-btn`} onClick={exit}>
                退出
              </div>
            )}
          </div>
        </div>
        <div className="Editor-inner">
          <Editor
            theme={'cxd'}
            preview={store.preview}
            isMobile={store.isMobile}
            value={store.schema}
            onChange={onChange}
            onPreview={() => {
              store.setPreview(true);
            }}
            onSave={save}
            className="is-fixed"
            $schemaUrl={schemaUrl}
            showCustomRenderersPanel={true}
            amisEnv={{
              fetcher: store.fetcher,
              notify: store.notify,
              alert: store.alert,
              copy: store.copy
            }}
          />
        </div>
      </div>
    );
  })
);
